package com.ysxsoft.wdg.upversion;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;

import com.socks.library.KLog;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.constant.MCConfig;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.APK_update;

/**
 * 自动更新Apk文件的服务
 */

public class ApkUpdateService extends IntentService {

    private static final String TAG = "APKUpdateService";
    private static final String appName = "wdg.apk";

    public static String APK_UPDATE = "http://wdg.sanzhima.cn/woniu/wdg.apk";



    public ApkUpdateService() {
        super("ApkUpdateService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        download();
    }

    private void download() {
        try {
            URL url = new URL(APK_UPDATE);
            //打开连接
            URLConnection conn = url.openConnection();
            //打开输入流
            InputStream is = conn.getInputStream();
            //获得长度
            int contentLength = conn.getContentLength();
            KLog.e("开始下载");
            String dirName = Environment.getExternalStorageDirectory() + File.separator;
            File file = new File(dirName);
            //不存在创建
            if (!file.exists() || file.length() == 0) {
                file.mkdir();
            }
            //下载后的文件名
            String fileName = dirName + appName;
            File file1 = new File(fileName);
            if (file1.exists()) {
                file1.delete();
            }
            //创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            sendNotification(0);
            KLog.e("开始下载"+0);
            EventBus.getDefault().post(new CommentEvent(APK_update));
            //写数据
            int downloadLen = 0;
            while ((len = is.read(bs)) != -1) {
                downloadLen += len;
                int progress = (int) (downloadLen * 100.0 / contentLength);
                KLog.e("开始下载"+progress);
                sendNotification(progress);
                EventBus.getDefault().post(new ProgressEvent(progress));
                os.write(bs, 0, len);
            }
            sendNotification(100);

            //完成后关闭流
            os.close();
            is.close();

            setPermission(file1.getAbsolutePath());//提升读写权限
            installApk(file1);//打开安装页面
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void installApk(File file) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri = FileProvider.getUriForFile(ApkUpdateService.this,
                        MCConfig.APP_FILEPROVIDER, file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(
                        new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                                "/"+appName)),
                        "application/vnd.android.package-archive");
            }
            startActivity(intent);
        } catch (Exception e) {
            KLog.e(TAG, "onResponse: " + e.toString());
        }
    }


    private int temp = -1;
    private void sendNotification(int progress) {
        if (temp == progress)
            return;
        temp = progress;
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher1)
                .setContentTitle("正在升级")
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setContentText(progress == 100 ? "下载完成" : "已下载" + progress + "%");
        Notification build = builder.build();
        notificationManager.notify(1, build);
    }


    //添加运行时权限
    private void setPermission(String path) {
        KLog.e(TAG, "setPermission: " + path);
        String command = "chmod" + "777" + " " + path;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
            KLog.e(TAG, "setPermission: " + command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
